#include "Sock.hpp"
#include "Protocol.hpp"
#include <iostream>

using namespace myself ; 


static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " ServerIP ServerPort\n" << std::endl;
}




int main(int argc, char* argv[])
{
    std::cout << "debug" << std::endl ;
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    Sock sock ;
    int sockfd = sock.Socket() ;
    //std::cout << "Connect waiting..... " << std::endl ;
    if(! sock.Connect(sockfd, server_ip , server_port)) 
    {
        std::cerr << "Connect error " << std::endl ;
        exit(2);
    }
    std::cout << "Connect success " << std::endl ;
    bool quit = false ;
    std::string buffer ; 
    while(!quit)
    {
        // 
        Request req ; 
        std::cout << "Please Enter #" ; 
        std::cin >> req._x >> req._op >> req._y ; 
        std::string s = req.Serialize();
        s = Encode(s);
        Send(sockfd, s);

        while(true)
        {
            bool res = Recv(sockfd, &buffer);
            if(!res)
            {
                quit = true ; 
                break ; 
            }
            std::string package = Decode(buffer);
            if(package.empty())
            {
                continue ; 
            }
            Response resp ; 
            resp.Deserialized(package);
            std::string err ; 

            switch(resp._code)
            {
                case 1 :
                    err = "除0错误";
                    break;
                case 2 : 
                    err = "模0错误";
                    break;
                case 3 :
                    err = "非法操作";
                    break; 
                default : 
                    std::cout <<  resp._x << resp._op << resp._y << resp._result << "[success]" << std::endl ; 
                    break; 
            }
            if(!err.empty())
            {
                std::cerr << err << std::endl ; 
            }
            break; 
        }
    }
    close(sockfd) ; 
    return 0 ; 
}
